const express = require('express')
// 引入cors中间件
const cors = require('cors')

const app = express()

app.use(express.static('./public'))
app.use(express.urlencoded({ extended: false }))
// 这个中间件就负责在预请求的时候,往响应主体中添加属性Access-Control-Allow-Origin
// app.use(cors())

app.get('/a/:id?', (req, res) => {
  // console.log(req.query) //获取查询字符串
  // console.log(req.params) //获取路由参数
  // res.send('const str = "响应了"')
  // res.send('fn("响应了")')
  // const { callback } = req.query
  // res.send(`${callback}("响应了")`) // => fn("响应了")
  const { callback } = req.query
  const arr = ['a', 'b', 'c']
  res.send(`${callback}(${JSON.stringify(arr)})`)
  // console.log(`${callback}(${JSON.stringify(arr)})`)
})

app.post('/b', (req, res) => {
  console.log(req.body)
  res.send('响应了')
})

app.post('/verifyUsername', (req, res) => {
  const arr = ['西门海静', '东方成板', '欧阳猫哥', '钢铁晨星']

  const { username } = req.body
  // 如果数组中有指定元素,则返回true,否则返回false
  const result = arr.includes(username)

  if (result) {
    res.send({ code: 1, message: '用户名不可用' })
  } else {
    res.send({ code: 2, message: '用户名可用' })
  }
})

app.listen(5000)
